package com.btm.mcpserver;

import com.btm.entity.Organization;
import com.btm.service.OrganizationService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 机构信息MCP服务工具类
 */
@Component
public class OrganizationMcpServer {
    private static final Logger log = LoggerFactory.getLogger(OrganizationMcpServer.class);

    @Autowired
    private OrganizationService organizationService;

    /**
     * 根据机构名称查询机构信息
     * 
     * @param name 机构名称
     * @return 查询结果（Markdown表格格式）
     */
    @Tool(description = "根据机构名称查询机构信息，返回Markdown表格格式的结果")
    public String queryOrganizationByName(String name) {
        log.info("收到机构查询请求，机构名称: {}", name);
        try {
            List<Organization> organizations = null;
            
            // 判断传入参数是否为纯数字
            if (isNumeric(name)) {
                log.info("检测到纯数字参数，优先按机构ID查询: {}", name);
                try {
                    Long orgId = Long.parseLong(name);
                    Organization organization = organizationService.findByOrgId(orgId);
                    if (organization != null) {
                        organizations = List.of(organization);
                        log.info("通过机构ID查询成功");
                    }
                } catch (NumberFormatException e) {
                    log.warn("数字转换失败，将使用名称查询: {}", e.getMessage());
                }
            }
            
            // 如果不是纯数字或通过ID查询未找到结果，则使用名称查询
            if (organizations == null) {
                log.info("使用机构名称查询: {}", name);
                organizations = organizationService.findByName(name);
            }
            
            return buildResult(organizations);
        } catch (Exception e) {
            log.error("查询机构信息出错", e);
            return "查询机构信息出错: " + e.getMessage();
        }
    }
    
    /**
     * 判断字符串是否为纯数字
     * 
     * @param str 待判断字符串
     * @return 是否为纯数字
     */
    private boolean isNumeric(String str) {
        if (str == null || str.trim().isEmpty()) {
            return false;
        }
        try {
            Long.parseLong(str.trim());
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public String buildResult(List<Organization> organizations) {
        if (organizations.isEmpty()) {
            return "未找到匹配的机构信息";
        }
        // 将结果转换成markdown的表格形式，列名：机构ID、机构名称、上级机构ID
        StringBuilder result = new StringBuilder("""
                    | 机构ID | 机构名称 | 上级机构ID |
                    | --- | --- | --- |
                    """);
        for (Organization organization : organizations) {
            result.append("| ").append(organization.getId()).append(" | ").append(organization.getName()).append(" | ").append(organization.getParentId()).append(" |\n");
        }
        log.info("机构信息查询结果: \n{}", result);
        return result.toString();
    }
    
    /**
     * 根据机构ID集合查询其直接下级机构
     * 
     * @param parentIds 上级机构ID集合
     * @return 查询结果（Markdown表格格式，只包含机构ID和机构名称）
     */
    @Tool(description = "根据机构ID集合查询其直接下级机构，返回Markdown表格格式的结果，只包含机构ID和机构名称")
    public String querySubOrganizationsByParentIds(List<Integer> parentIds) {
        log.info("收到查询下级机构请求，上级机构ID: {}", parentIds);
        try {
            // 验证输入参数
            if (parentIds == null || parentIds.isEmpty()) {
                return "上级机构ID集合不能为空";
            }
            
            List<Organization> subOrganizations = organizationService.findByParentIds(parentIds);
            if (subOrganizations.isEmpty()) {
                return "未找到下级机构信息";
            }
            
            // 将结果转换成markdown的表格形式，只包含机构ID和机构名称
            StringBuilder result = new StringBuilder("""
                    | 机构ID | 机构名称 |
                    | --- | --- |
                    """);
            for (Organization organization : subOrganizations) {
                result.append("| ").append(organization.getId()).append(" | ").append(organization.getName()).append(" |\n");
            }
            log.info("下级机构查询结果: \n{}", result);
            return result.toString();
        } catch (Exception e) {
            log.error("查询下级机构出错", e);
            return "查询下级机构出错: " + e.getMessage();
        }
    }
}